from flask import Blueprint, request, jsonify
from src.models.models import db, DownloadTask, Subscription
from sqlalchemy import desc

downloads_bp = Blueprint('downloads', __name__)

@downloads_bp.route('/downloads', methods=['GET'])
def get_downloads():
    """获取下载任务列表"""
    try:
        # 获取查询参数
        status_filter = request.args.get('status', '')
        name_filter = request.args.get('name', '').strip()  # 新增：影视名称筛选
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('per_page', 20))
        
        # 构建查询
        query = DownloadTask.query
        
        # 状态筛选
        if status_filter and status_filter != 'all':
            query = query.filter(DownloadTask.status == status_filter)
        
        # 影视名称筛选
        if name_filter:
            query = query.filter(DownloadTask.name.like(f"%{name_filter}%"))
        
        # 分页查询
        pagination = query.order_by(desc(DownloadTask.created_at)).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        tasks = pagination.items
        
        return jsonify({
            'success': True,
            'data': {
                'tasks': [task.to_dict() for task in tasks],
                'pagination': {
                    'page': page,
                    'per_page': per_page,
                    'total': pagination.total,
                    'pages': pagination.pages,
                    'has_prev': pagination.has_prev,
                    'has_next': pagination.has_next
                }
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@downloads_bp.route('/downloads/<int:task_id>/retry', methods=['POST'])
def retry_download(task_id):
    """重新下载单个任务"""
    try:
        from src.services.downloader import retry_download_task
        result = retry_download_task(task_id)
        
        if result['success']:
            return jsonify({
                'success': True,
                'message': result['message']
            })
        else:
            return jsonify({
                'success': False,
                'message': result.get('message', '重新下载失败')
            }), 500
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@downloads_bp.route('/downloads/retry', methods=['POST'])
def batch_retry_downloads():
    """批量重新下载"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                'success': False,
                'message': '请求数据格式错误'
            }), 400
            
        task_ids = data.get('task_ids', [])
        
        if not task_ids:
            return jsonify({
                'success': False,
                'message': '请选择要重新下载的任务'
            }), 400
        
        # 验证task_ids格式
        if not isinstance(task_ids, list):
            return jsonify({
                'success': False,
                'message': '任务ID列表格式错误'
            }), 400
        
        # 批量重新下载
        from src.services.downloader import batch_retry_download_tasks
        result = batch_retry_download_tasks(task_ids)
        
        if result['success']:
            return jsonify({
                'success': True,
                'message': result['message'],
                'data': result['data']
            })
        else:
            return jsonify({
                'success': False,
                'message': result.get('message', '批量重新下载失败')
            }), 500
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@downloads_bp.route('/downloads/stats', methods=['GET'])
def get_download_stats():
    """获取下载统计信息"""
    try:
        stats = {
            'total': DownloadTask.query.count(),
            'waiting_create': DownloadTask.query.filter_by(status='waiting_create').count(),
            'created_success': DownloadTask.query.filter_by(status='created_success').count(),
            'created_failed': DownloadTask.query.filter_by(status='created_failed').count(),
            'task_duplicate': DownloadTask.query.filter_by(status='task_duplicate').count()
        }
        
        return jsonify({
            'success': True,
            'data': stats
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@downloads_bp.route('/downloads/queue/process', methods=['POST'])
def process_download_queue():
    """手动处理下载队列"""
    try:
        from src.services.downloader import process_download_queue
        processed_count = process_download_queue()
        
        return jsonify({
            'success': True,
            'message': f'处理了 {processed_count} 个下载队列任务',
            'data': {
                'processed_count': processed_count
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@downloads_bp.route('/downloads/queue/status', methods=['GET'])
def get_queue_status():
    """获取下载队列状态"""
    try:
        from src.services.queue_processor import get_queue_status
        status = get_queue_status()
        
        return jsonify({
            'success': True,
            'data': status
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

